package com.genius.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.genius.annotation.Log;
import com.genius.annotation.PreFuncAuth;
import com.genius.core.JSONResult;
import com.genius.enums.BusinessType;
import com.genius.enums.ResponseType;
import com.genius.service.*;
import com.genius.system.bo.*;
import com.genius.system.pojo.Dept;
import com.genius.system.pojo.Menu;
import com.genius.system.pojo.Role;
import com.genius.system.pojo.User;
import com.genius.utils.PageUtils;
import com.genius.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("role")
@Api(value = "角色管理接口", tags = {"用于角色管理的接口"})
public class RoleController {
    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private RoleDeptService roleDeptService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private DeptService deptService;

    @GetMapping("selectAllRole")
    @ApiOperation(value = "查询角色（所有角色）",notes = "查询所有角色", httpMethod = "GET")
    public JSONResult selectAllRole() {
        List<Role> list = roleService.selectAllRole();
        return JSONResult.ok(list);
    }

    @PostMapping("selectRoleById")
    @PreFuncAuth("SYS:ROLE:SELECT")
    @ApiOperation(value = "查询角色（根据ID查询）",notes = "根据ID查询角色", httpMethod = "POST")
    public JSONResult selectRoleById(@Valid @RequestBody SelectRoleByIdBO selectRoleByIdBO) {
        Role role = roleService.selectRoleById(selectRoleByIdBO.getRoleId());
        User user = SecurityUtils.getUser();
        List<Menu> menuList;
        if(user.getIsRoot()){
            menuList = menuService.selectAllMenu(new Menu());
        }else{
            HashMap<String,Object> hashMap = new HashMap<>();
            hashMap.put("userId",user.getUserId());
            menuList = menuService.selectMenuByUserId(hashMap);
        }
        Dept dept = new Dept();
        List<Dept> deptList = deptService.selectAllDept(dept);
        Map<String,Object> result = new HashMap<>();
        result.put("role",role);
        result.put("menuCheckedKeys",menuService.selectMenuByRoleId(selectRoleByIdBO.getRoleId()));
        result.put("menuList",menuList);
        result.put("deptCheckedKeys",roleDeptService.selectDeptByRoleId(selectRoleByIdBO.getRoleId()));
        result.put("deptList",deptList);
        return JSONResult.ok(result);
    }

    @PostMapping("/selectRoleByPage")
    @ApiOperation(value = "查询角色（分页查询）",notes = "查询角色分页数据", httpMethod = "POST")
    @PreFuncAuth("SYS:ROLE:SELECT")
    public JSONResult selectRoleByPage(@Valid @RequestBody SelectRoleByPageBO selectRoleByPageBO) {
        int pageNum = selectRoleByPageBO.getPageNum();
        int pageSize = selectRoleByPageBO.getPageSize();
        Role role = JSONUtil.parse(selectRoleByPageBO).toBean(Role.class);
        PageUtils.startPage(pageNum,pageSize);
        List<Role> roleList = roleService.selectRoleByPage(role);
        Map<String,Object> result = PageUtils.getResultTableData(roleList);
        return JSONResult.ok(result);
    }

    @PostMapping("/insertRole")
    @ApiOperation(value = "添加角色",notes = "添加角色", httpMethod = "POST")
    @PreFuncAuth("SYS:ROLE:INSERT")
    public JSONResult insertRole(@Valid @RequestBody InsertRoleBO insertRoleBO) {
        //查询角色名称是否存在
        boolean isExist = roleService.selectRoleNameIsExist(insertRoleBO.getRoleName());
        if(isExist){
            return JSONResult.errorCustom(ResponseType.ROLE_NAME_EXIST_ERROR);
        }
        if(insertRoleBO.getMenuIds().length > 0){
            boolean menuIdIsExist = menuService.selectMenuIsExistByMenuIds(insertRoleBO.getMenuIds());
            if(!menuIdIsExist){
                return JSONResult.errorCustom(ResponseType.MENU_NOT_EXIST_ERROR);
            }
        }
        if(insertRoleBO.getDeptIds().length > 0){
            boolean deptIdIsExist = deptService.selectDeptIsExistByDeptIds(insertRoleBO.getDeptIds());
            if(!deptIdIsExist){
                return JSONResult.errorCustom(ResponseType.DEPT_NOT_EXIST_ERROR);
            }
        }
        Role role = JSONUtil.parse(insertRoleBO).toBean(Role.class);
        Long roleId = IdUtil.getSnowflake().nextId();
        role.setRoleId(roleId);
        role.setCreateBy(SecurityUtils.getUsername());
        int rows = roleService.insertRole(role);
        roleMenuService.insertRoleMenu(role);
        roleDeptService.insertRoleDept(role);
        Map<String,Object> result = new HashMap<>();
        result.put("rows",rows);
        return JSONResult.ok(result);
    }

    @PostMapping("/updateRole")
    @ApiOperation(value = "修改角色",notes = "修改角色", httpMethod = "POST")
    @PreFuncAuth("SYS:ROLE:UPDATE")
    public JSONResult updateRole(@Valid @RequestBody UpdateRoleBO updateRoleBO) {
        if(updateRoleBO.getDeptIds() != null && updateRoleBO.getDeptIds().length > 0){
            boolean deptIdIsExist = deptService.selectDeptIsExistByDeptIds(updateRoleBO.getDeptIds());
            if(!deptIdIsExist){
                return JSONResult.errorCustom(ResponseType.DEPT_NOT_EXIST_ERROR);
            }
        }
        if(updateRoleBO.getMenuIds() != null && updateRoleBO.getMenuIds().length > 0){
            boolean menuIdIsExist = menuService.selectMenuIsExistByMenuIds(updateRoleBO.getMenuIds());
            if(!menuIdIsExist){
                return JSONResult.errorCustom(ResponseType.MENU_NOT_EXIST_ERROR);
            }
        }
        Role role = JSONUtil.parse(updateRoleBO).toBean(Role.class);
        role.setUpdateBy(SecurityUtils.getUsername());
        int rows = roleService.updateRole(role);
        roleMenuService.insertRoleMenu(role);
        roleDeptService.insertRoleDept(role);
        Map<String,Object> result = new HashMap<>();
        result.put("rows",rows);
        return JSONResult.ok(result);
    }

    @PostMapping("/deleteRoleByIds")
    @ApiOperation(value = "删除角色",notes = "删除角色", httpMethod = "POST")
    @PreFuncAuth("SYS:ROLE:DELETE")
    @Log(title = "删除角色", businessType = BusinessType.DELETE)
    public JSONResult deleteRoleByIds(@Valid @RequestBody DeleteRoleByIdsBO deleteRoleByIdsBO) {
        int rows = roleService.deleteRoleByIds(deleteRoleByIdsBO.getRoleIds());
        Map<String,Object> result = new HashMap<>();
        result.put("rows",rows);
        return JSONResult.ok(result);
    }
}
